package com.zh.async.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 异步任务数据源配置
 * @Author：zhanghang
 * @Date：2025/8/24
 */
@Configuration
@ConditionalOnProperty(name = "async.datasource.enabled", havingValue = "true", matchIfMissing = true)
@MapperScan(basePackages = "com.zh.async.mapper", sqlSessionFactoryRef = "asyncSqlSessionFactory")
public class AsyncDataSourceConfiguration {
    
    /**
     * 配置数据源
     */
    @Bean(name = "asyncDataSource")
    @Primary
    @ConfigurationProperties(prefix = "async.datasource")
    public DataSource asyncDataSource() {
        return new DruidDataSource();
    }
    
    /**
     * 配置SqlSessionFactory
     */
    @Bean(name = "asyncSqlSessionFactory")
    @Primary
    public SqlSessionFactory asyncSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(asyncDataSource());
        
        // 设置MyBatis配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCallSettersOnNulls(true);
        sessionFactory.setConfiguration(configuration);
        
        // 设置Mapper XML文件位置
        sessionFactory.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")
        );
        
        return sessionFactory.getObject();
    }
}
